//
//  K_LineWebViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/11/16.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "K_LineWebViewController.h"
#import "WKWebView+AccessoryHiding.h"
#import "ExceptionView.h"
#import "AppDelegate.h"
#import "HomeBaseModel.h"
#import <JavaScriptCore/JavaScriptCore.h>

#define HEIGHT_IPHoneX   0
@interface K_LineWebViewController  ()<UIScrollViewDelegate,UIAlertViewDelegate,UIWebViewDelegate>

@property (nonatomic, strong) UIWebView *webView;

@property (nonatomic,strong) ExceptionView * exceptionView;


@property (strong, nonatomic) JSContext *context;

@end

@implementation K_LineWebViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createUI];
    [self prefersStatusBarHidden];
    [self performSelector:@selector(setNeedsStatusBarAppearanceUpdate)];
    if (_strTitle) {
        self.title=_strTitle;
    }
}

- (UIView*)viewForZoomingInScrollView:(UIScrollView*)scrollView{ // 实现代理方法， step 3
    return nil;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //初始化content
    JSContext *contest =[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    
    //    choiceTeam
    
    // 打印异常,由于JS的异常信息是不会在OC中被直接打印的,所以我们在这里添加打印异常信息,
    contest.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
    };
    WS(weakSelf);
    contest[@"clickBtn"] =
    ^()
    {
        
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    };
    contest[@"back"] =
    ^()
    {
        
        
        [weakSelf.navigationController popViewControllerAnimated:YES];
        
    };
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [super viewWillAppear:animated];
    self.webView.scrollView.delegate = self; // 注册代理， step 2
    self.webView.scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag; // 当拖动时移除键盘
    //TODO:加载
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    [self.webView reload];
   
    //TODO:kvo监听，获得页面title和加载进度值
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];
    
    
    //注册键盘弹出通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    
    //注册键盘隐藏通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
 
}

-(void)DoJavaScript:(NSString *)jsString{
    
    [self.webView stringByEvaluatingJavaScriptFromString:jsString];
    
}

-(void)delayMethod{
    
    [BKIndicationView dismiss];
    
}

-(UIWebView *)webView
{
    if (_webView == nil)
    {
        _webView = [[UIWebView alloc]init];
        _webView.backgroundColor = [UIColor whiteColor];
    }
    return _webView;
}


-(void)createUI{
    
    self.view.backgroundColor=[UIColor whiteColor];
    [self.view addSubview:self.webView];
    
    if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
        self.webView.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT+HEIGHT_IPHoneX);
    }else{
        self.webView.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT);
    }
    
    self.webView.delegate = self;
    
    [self createBackBtn];
    
}

-(void)createBackBtn{
    UIButton * backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setTitle:@"" forState:UIControlStateNormal];
    [backBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];
    backBtn.imageView.frame=CGRectMake(0, 0, 18, 32);
//    [backBtn setImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateNormal];
    [self.view addSubview:backBtn];
    backBtn.backgroundColor=[UIColor clearColor];
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    backBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(TopBackButtonHeight);
        make.left.equalTo(self.view.mas_left).offset(-20);
        
        make.height.equalTo(@(40));
        make.width.equalTo(@(100));
    }];
    
    UIButton * sbackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [sbackBtn setTitle:@"" forState:UIControlStateNormal];
    [sbackBtn setTitleColor:RGB(255, 255, 255) forState:UIControlStateNormal];
    [sbackBtn addTarget:self action:@selector(goBackAction) forControlEvents:UIControlEventTouchUpInside];
    sbackBtn.imageView.frame=CGRectMake(0, 0, 18, 32);
    //    [backBtn setImage:[UIImage imageNamed:@"图层-6"] forState:UIControlStateNormal];
    [self.view addSubview:sbackBtn];
    sbackBtn.backgroundColor=[UIColor clearColor];
    sbackBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    sbackBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [sbackBtn mas_makeConstraints:^(MASConstraintMaker *make) {

        make.height.mas_equalTo(kTabBarHeight);
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
    
}




-(void)goBackAction{
    [self.navigationController popViewControllerAnimated:YES];
}


//1.转换编码
-(NSURL *)GetNSURLWithURL:(NSString *)sUrl{
    NSURL *url = [NSURL URLWithString:sUrl];
    return url;
}

//2.除去空格
+(NSString *)returnFormatString:(NSString *)str
{
    return [str stringByReplacingOccurrencesOfString:@" "withString:@" "];
}

/*浏览器后退*/
- (void)clickGoBackBtn{
    if(self.webView.canGoBack){
        [self.webView goBack];
    }
}

/*浏览器前进*/
- (void)clickGoForwardBtn{
    if(self.webView.canGoForward){
        [self.webView goForward];
    }
}

#pragma mark - UIWebViewDelegate代理方法


-(void)showAgainLoad{
    
    __weak __typeof__ (self) wself = self;
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络错误，请重试！" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        
        [wself loadApi];
        
    }]];
    
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

-(void)loadApi{
    //TODO:加载
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
    
}

#pragma mark KVO的监听代理
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败,失败原因:%@",[error description]);
    [BKIndicationView dismiss];
    
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"网页加载内容进程终止");
    [BKIndicationView dismiss];
}

#pragma mark 移除观察者
- (void)dealloc
{
    //    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

//键盘弹出后将视图向上移动
-(void)keyboardWillShow:(NSNotification *)note{
    
    NSDictionary * info = [note userInfo];
    CGSize keyboardSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    
    NSTimeInterval animationDuration = 0.00f;
    [UIView beginAnimations:@"ResizeView" context:nil];
    [UIView setAnimationDuration:animationDuration];
    
    if (keyboardSize.height>400) {
        
        if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
            self.webView.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT  - 400+HEIGHT_IPHoneX);
            
        }else{
            self.webView.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT - 400);
            
        }
        NSLog(@"web的高度----%f",G_SCREENHEIGHT - 400);
    }else{
        
        if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
            self.webView.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT - keyboardSize.height+HEIGHT_IPHoneX);
            
        }else{
            self.webView.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT - keyboardSize.height);
            
        }
        
        
        NSLog(@"web的高度----%f",G_SCREENHEIGHT - keyboardSize.height);
    }
    
    
    NSLog(@"---键盘的高度---%f",keyboardSize.height);
    
    [UIView commitAnimations];
    
    
}


//键盘隐藏后将视图恢复到原始状态
-(void)keyboardWillHide:(NSNotification *)note{
    
    NSTimeInterval animationDuration = 0.30f;
    
    [UIView beginAnimations:@"ResizeView" context:nil];
    
    [UIView setAnimationDuration:animationDuration];
    
    
    if (IS_iPhoneX||IS_iPhone_Xr||IS_iPhone_Xs||IS_iPhone_Xs_Max) {
        self.webView.frame=CGRectMake(0, -HEIGHT_IPHoneX, G_SCREENWIDTH, G_SCREENHEIGHT+HEIGHT_IPHoneX);
        
    }else{
        self.webView.frame=CGRectMake(0, 0, G_SCREENWIDTH, G_SCREENHEIGHT);
        
    }
    [UIView commitAnimations];
}


@end



















